package filter;

import bean.pojo.User;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import service.LogService;
import service.UsersService;
import service.impl.LogServiceImpl;
import service.impl.UsersServiceImpl;
import servlet.user.LoginServlet;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;

/**
 * filter
 * User: mcw
 * Date: 2024/12/24 下午3:44
 * motto:   春天（spring）没有虫子（bug)
 * Description:
 * Version: V1.0
 */
@WebFilter(filterName = "LogManagementLogFilter", urlPatterns = "/*") // 修改为拦截所有请求，然后在代码中进行具体判断过滤
public class LogManagementLogFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 过滤器初始化方法，如果有需要初始化的资源可以在这里进行，当前示例暂无需额外初始化操作
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //请求路径
        String requestURI = request.getRequestURI();
        System.out.println("请求URL: "+requestURI);
        //请求方法
        String method = request.getMethod();
        System.out.println("请求方法: "+method);
        if (!requestURI.contains("/user/login") &&!requestURI.contains("/register/registerUser")) { // 判断请求URI是否包含登录或注册相关标识，如果不包含则进行日志记录
            if (!requestURI.equals("/")){
                User user = LoginServlet.loginUser;
                System.out.println("LogManagementLogFilter:user:"+user);
                if (user.getUserId()!= null) {
                    //插入日志信息
                    LogService logService = new LogServiceImpl();
                    logService.insert(user.getUserId(),user.getUserName(),"访问"+requestURI, LocalDateTime.now());
                }
            }

        }
        // 如果是登录或注册相关请求，直接放行，不进行日志记录操作
        filterChain.doFilter(servletRequest, servletResponse);

    }

    @Override
    public void destroy() {
        // 过滤器销毁方法，如果有需要释放的资源可以在这里进行，当前示例暂无需额外销毁操作
    }
}
